package com.iscas.green.extralindextest.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 安全过滤器
 * 通过配置类手动注册
 */
public class SecurityFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(SecurityFilter.class);
    
    private String secretHeaderName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        secretHeaderName = filterConfig.getInitParameter("secretHeaderName");
        if (secretHeaderName == null) {
            secretHeaderName = "X-API-Secret";
        }
        log.info("SecurityFilter初始化，secretHeaderName={}", secretHeaderName);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String secretValue = httpRequest.getHeader(secretHeaderName);
        log.info("检查安全头: {}, 值: {}", secretHeaderName, secretValue);
        
        // 简单的安全检查，可以根据实际需求调整
        if (secretValue == null || !secretValue.equals("feign-servlet-demo")) {
            log.warn("安全检查失败，请求被拒绝");
            httpResponse.setContentType("text/html;charset=UTF-8");
            httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            httpResponse.getWriter().write("<html><body>");
            httpResponse.getWriter().write("<h2>访问被拒绝</h2>");
            httpResponse.getWriter().write("<p>需要提供有效的安全头: " + secretHeaderName + "</p>");
            httpResponse.getWriter().write("</body></html>");
            return;
        }
        
        // 安全检查通过，继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("SecurityFilter销毁");
    }
} 